import { AuthApi, type LoginRO, type TokenVO } from '@/api';
import axios from 'axios';

class AuthService {
    private axiosInstance = axios.create();
    private authApi = new AuthApi(undefined, import.meta.env.VITE_API_URL, this.axiosInstance);

    // 使用 getter 动态检查登录状态
    get isLoggedIn(): boolean {
        const accessToken = localStorage.getItem("token");
        console.log("当前 token:", accessToken); // 调试日志
        return accessToken !== null;
    }

    private saveToken(token: string) {
        console.log("保存 token:", token); // 调试日志
        if (!token) {
            throw new Error("Token 数据不完整");
        }
        localStorage.setItem("token", token);
    }

    private clearToken() {
        localStorage.removeItem("token");
        localStorage.removeItem("refresh_token");
    }

    login(loginRo: LoginRO) {
        return this.authApi.login(loginRo).then((res) => {
            console.log("登录响应数据:", res.data); // 检查返回的数据
            if (!res.data.token) {
                throw new Error("Token 数据不完整");
            }
            this.saveToken(res.data.token);
            return res;
        });
    }

    refreshToken() {
        let refreshToken = localStorage.getItem("refresh_token");
        return this.authApi.refresh(refreshToken!).then((res) => {
            // 假设 this.saveToken 必须接收一个 string
            if (res.data.token) {
                this.saveToken(res.data.token);
            } else {
                console.error('Token is undefined.');
                // 根据需求处理：抛出异常、记录日志、或者设置默认值
            }

            return res;
        });
    }

    logout() {
        this.clearToken();
    }
}

export const authService = new AuthService();